//
//  CZUserCountViewModel.swift
//  weiBo
//
//  Created by apple on 16/5/13.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZUserCountViewModel: NSObject {
    //单例
    static let sharedUserAccount : CZUserCountViewModel = CZUserCountViewModel()
    //获取归档对象
    override init() {
        super.init()
        userAcount = CZUserAcount.loadUserAccount()
    }
    
    var isLogin :Bool{
        return access_token != nil
    }
    
    var access_token: String? {
        guard let token = userAcount?.access_token else {
            return nil
        }
        
        let result = userAcount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending{
            return token
        }else{
            return nil
        }
        
    
    }
    
    
    //接受数据
    var userAcount:CZUserAcount?

    //通过code获得token
    func requestAccessToken(code : String ,complete:(isSuccess : Bool)->()){
        CZNetWorkTools.shareTools.requestAccessToken(code) { (response, error) -> () in
            if error != nil{
                print(error)
                complete(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String : AnyObject] else{
                complete(isSuccess: false)
                return
            }
            
            let userCount = CZUserAcount(dict: dict)
            self.requestUserInfo(userCount,complete: complete)
        }
    }
    func requestUserInfo(userAccount : CZUserAcount,complete:(isSuccess : Bool)->()){
            CZNetWorkTools.shareTools.requestUserInfo(userAccount) { (response, error) -> () in
                if error != nil {
                    print(error)
                    complete(isSuccess: false)

                    return
                }
                guard let dict = response as? [String : AnyObject] else{
                    complete(isSuccess: false)

                    return
                }
                
                userAccount.name = dict["name"] as? String
                userAccount.avatar_large = dict["avatar_large"] as? String
                self.userAcount = userAccount
                //归档
                userAccount.saveUserAcount()
                //  归档数据
                let result = userAccount.saveUserAcount()

                if result {
                    complete(isSuccess: true)
                
                }else{
                    complete(isSuccess: false)

                }
                
            }

    }
    
}
